package com.leo.business;

import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.leo.dao.UserDao;
import com.leo.entity.User;
import com.leo.formbean.UserForm;
import com.leo.util.AccessTokenUtil;
import com.leo.util.InnerObjectUtile;
import com.leo.util.JiaowuNetBug;
import com.leo.util.MemcachedUtil;
import com.leo.util.RegexUtil;
import com.leo.vo.AccessTokenResult;
import com.leo.vo.Result;

@Transactional
public class UserBusinessImp implements UserBusiness {

	@Resource
	private UserDao userDao;
	@Resource
	private JiaowuNetBug jiaowuNetBug;
	private RegexUtil regexUtil = new RegexUtil();

	@Override
	public Result regist(UserForm userForm){
		try {
			String username = userForm.getUsername(),
					password = userForm.getPassword(),
					passwordComfirm = userForm.getPasswordComfirm(),
					appURL = userForm.getAppURL();
			if(!passwordComfirm.equals(password)) {
				return new Result("failure", "两次密码不一致");
			}
			if (!regexUtil.userNameLegal(username, 4, 20)) {
				return new Result("failure", "要求用户名英文开头的长度为4至20的合法字符");
			}
			if(!regexUtil.userPasswordLegal(password, 6, 20)) {
				return new Result("failure", "要求用户名长度为6至20的合法字符");
			}
			if(!regexUtil.isHttpURL(appURL)) {
				return new Result("failure", "网站地址不合法");
			}
			if(userDao.findUser(username) != null){
				return new Result("failure", "用户名已存在");
			}
			User user = new User();
			user.setAppURL(appURL);
			user.setOid(UUID.randomUUID().toString());
			user.setUsername(username);
			user.setPassword(password);
			user.setQueryRight("no");
			userDao.addUser(user);
		} catch (NullPointerException ex) {
			return new Result("failure", "字段不能为空");
		}
		Map<String, String> session = InnerObjectUtile.SESSION.getMap();
		session.put("username",userForm.getUsername());
		if(userForm.getUseCookie()){
			Map<String, String> cookie = InnerObjectUtile.COOKIES.getMap();
			cookie.put("username", userForm.getUsername());
		}
		return Result.success();
	}

	@Override
	public boolean isLogin(){
		return InnerObjectUtile.SESSION.getMap().containsKey("username");
	}

	@Override
	public Result Login(UserForm userForm){
		//check login
		User user = userDao.findUser(userForm.getUsername());
		if(user == null){
			return new Result("failure", "用户名不存在");
		}else if(  !userForm.getPassword().equals( user.getPassword() ) ){
			return new Result("failure", "密码错误");
		}
		Map<String, String> session = InnerObjectUtile.SESSION.getMap();
		session.put("username",userForm.getUsername());
		session.put("password", userForm.getPassword());
		if(userForm.getUseCookie()){
			Map<String, String> cookie = InnerObjectUtile.COOKIES.getMap();
			cookie.put("username", userForm.getUsername());
			cookie.put("password", userForm.getPassword());
		}
		return new Result("success", "登录成功");
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public void logout(){
		InnerObjectUtile.SESSION.getMap().remove("username");
	}


	@Override
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public AccessTokenResult getAccessToken(UserForm userForm){
		AccessTokenResult result = null;
		try {
			User user = userDao.findUser(userForm.getUsername());
			if(user.getPassword().equals(userForm.getPassword()) && "yes".equals(user.getQueryRight())){
				MemcachedUtil memcached = MemcachedUtil.getInstance();
				String ac = (String) memcached.get(userForm.getUsername());
				if(ac != null){
					return AccessTokenResult.success(ac);
				}
				result = AccessTokenResult.success(AccessTokenUtil.getAccessToken(user.getUsername(), user.getPassword()));
				memcached.add(result.getAccessToken(), userForm.getUsername(), 60*60*12);
				memcached.add(userForm.getUsername(), result.getAccessToken(), 60*60*12);
				return result;
			}else{
				result = AccessTokenResult.accountError;
				return result;
			}
		} catch (NullPointerException e) {
			result = AccessTokenResult.accountError;
		}catch (Exception e){
			result = AccessTokenResult.serverError;
		}
		return result;
	}

	@Override
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public boolean validateAccessToken(String accessToken){
		try {
			if(accessToken == null)
				return false;
			Object o = MemcachedUtil.getInstance().get(accessToken);
			if(o == null || o.equals(""))
				return false;
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public void getInfo() {
		Map<String, String> session = InnerObjectUtile.SESSION.getMap();
		Map<String, String> request = InnerObjectUtile.REQUEST.getMap();
		String username = session.get("username");
		User user = userDao.findUser(username);
		request.put("appURL", user.getAppURL());
		request.put("queryRight", user.getQueryRight());
	}

	@Override
	public Result updateInfo(UserForm userForm) {
		try{
			User user = userDao.findUser(userForm.getUsername());
			if(user.getPassword().equals(userForm.getOldPassword())){
				if(userForm.getPassword() != null && !userForm.getPassword().equals("")){
					user.setPassword(userForm.getPassword());
				}
				if(!user.getAppURL().equals(userForm.getAppURL())) {
					user.setQueryRight("no");
					user.setAppURL(userForm.getAppURL());
				}
				userDao.updateUser(user);
				return Result.success();
			}
			else{
				return Result.error("密码错误");
			}
		}catch (Exception e) {
			// TODO: handle exception
			return Result.error(e.getCause());
		}
		
	}
}
